package com.example.sensorapp;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;

import com.example.sensorapp.Services.SensorListenerService;

public class MainActivity extends Activity
{
	private boolean isStarted;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        isStarted = false;
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
    @Override
    protected void onResume()
    {
    	TextView isRunningTV = (TextView) findViewById(R.id.isRunningTV);
    	super.onResume();
    	isStarted = isServiceRunning();
    	
    	if (isStarted == false)
    	{
    		Intent serviceIntent = new Intent();
    		serviceIntent.setClass(this, SensorListenerService.class);
    		this.startService(serviceIntent);
    		isRunningTV.setText("Service is running");
    	}
    	else
    		isRunningTV.setText("Service is running");
    }
    
    @Override
    protected void onPause()
    {
    	super.onPause();
    }
    
    public void startStopService(View view)
    {
    	TextView isRunningTV = (TextView) findViewById(R.id.isRunningTV);
    	Intent serviceIntent = new Intent();
    	isStarted = isServiceRunning();
    	
    	if (isStarted == false)
    	{
    		serviceIntent.setClass(this, SensorListenerService.class);
    		this.startService(serviceIntent);
    		isRunningTV.setText("Service is running");
    		isStarted = true;
    	}
    	else 
    	{
    		serviceIntent.setClass(this, SensorListenerService.class);
    		this.stopService(serviceIntent);
    		isRunningTV.setText("Service is stopped");
    	}
    }
    
    private boolean isServiceRunning()
    {
    	ActivityManager manager = (ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);
    	
    	for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE))
    	{
    		if (SensorListenerService.class.getName().equals(service.service.getClassName()))
    			return true;
    	}
    	
    	return false;
    }
}
